package com.example.demo.service;

import com.alibaba.fastjson2.JSONObject;
import com.example.demo.auth.AESBase64Utils;
import com.example.demo.auth.IoTConsumer;
import com.example.demo.auth.IoTMessage;
import com.example.demo.config.IoTConfig;
import com.example.demo.websocket.WebSocketHandler;
import com.example.demo.service.UserDeviceBindingService;
import org.apache.pulsar.client.api.MessageId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class PulsarConsumerManager {
    private static final Logger logger = LoggerFactory.getLogger(PulsarConsumerManager.class);

    @Value("${iot.access-id}")
    private String iotAccessId;

    @Value("${iot.secret-key}")
    private String iotSecretKey;

    @Value("${iot.subscription-name}")
    private String iotSubscriptionName;

    private final WebSocketHandler webSocketHandler;
    private final UserDeviceBindingService userDeviceBindingService;
    private final ExecutorService executorService;

    public PulsarConsumerManager(WebSocketHandler webSocketHandler, UserDeviceBindingService userDeviceBindingService) {
        this.webSocketHandler = webSocketHandler;
        this.userDeviceBindingService = userDeviceBindingService;
        this.executorService = Executors.newSingleThreadExecutor();
    }

    @PostConstruct
    public void startConsuming() {
        executorService.submit(() -> {
            try {
                IoTConsumer iotConsumer = IoTConsumer.IOTConsumerBuilder.anIOTConsumer()
                        .brokerServerUrl(IoTConfig.brokerSSLServerUrl)
                        .iotAccessId(iotAccessId)
                        .iotSecretKey(iotSecretKey)
                        .subscriptionName(iotSubscriptionName)
                        .iotMessageListener(message -> {
                            MessageId msgId = message.getMessageId();
                            long publishTime = message.getPublishTime();
                            String payload = new String(message.getData());
                            IoTMessage iotMessage = JSONObject.parseObject(payload, IoTMessage.class);
                            String originalMsg = AESBase64Utils.decrypt(iotMessage.getData(), iotSecretKey.substring(8,24));
                            logger.info("IOT consume message======>>>>>>> messageId={}, publishTime={},  payload={}",
                                    msgId, publishTime, payload);
                            logger.info("IOT originalMsg:{}", originalMsg);

                            // 解析消息以获取 IMEI
                            JSONObject msgJson = JSONObject.parseObject(originalMsg);
                            String imei = msgJson.getJSONObject("subData").getString("deviceName");

                            // 查找与 IMEI 关联的 OpenID
                            String openId = userDeviceBindingService.getOpenidByImei(imei);

                            if (openId != null) {
                                // 发送消息给特定用户
                                webSocketHandler.sendMessageToUser(openId, originalMsg);
                                logger.info("Message sent to user with openId: {}, imei: {}", openId, imei);
                            } else {
                                logger.warn("No user found for IMEI: {}", imei);
                            }
                        }).build();
                iotConsumer.run();
            } catch (Exception e) {
                logger.error("Error starting Pulsar consumer", e);
            }
        });
        logger.info("Pulsar consumer startup initiated in background thread");
    }
}